package com.changkang.webim.controller;




import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.changkang.webim.common.MessageType;
import com.changkang.webim.common.Result;
import com.changkang.webim.model.Bevy;
import com.changkang.webim.model.Bevymember;
import com.changkang.webim.model.Chat;
import com.changkang.webim.model.Friend;
import com.changkang.webim.model.Group;
import com.changkang.webim.model.Notify;
import com.changkang.webim.model.User;
import com.changkang.webim.mqtt.MqttKit;
import com.changkang.webim.util.IdGenerate;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
public class UserController  extends  Controller{
	
	
	public void index() {
		if(getSessionAttr("user")==null) {
			render("login.jsp");
		}else {
		    render("chat.jsp");
		}
	} 
	
	public void chatView() {
		render("chat.jsp");
	}
	
	//登录成功后，需要先查看有无离线消息
	public void login() {
		String phone=getPara("phone");
		String password=getPara("password");
		if(StrKit.isBlank(phone)) {  
			renderJson(Result.fail("账号不能为空"));
		}else if(StrKit.isBlank(password)) {
			renderJson(Result.fail("密码不能为空"));
		}else {
			User user=User.dao.login(phone, password);
			if(user==null) {
				renderJson(Result.fail("账号或者密码错误"));
			}else {
				if(user.getStatus().equals("online")) {
					renderJson(Result.fail("该账号已在其他地方登录"));	
				}else {
					setSessionAttr("user", user);
					setSessionAttr("sessionid", getSession().getId());
					renderJson(Result.success("登录成功"));	
				}
			}
		}
	}
	
	public static void main(String[] args) {
		String s = "我是";
		String regex = "[\u4E00-\u9FA5]+";
		System.out.println(s.matches(regex));
	}
	
	public void reg() {
		//判断是否为汉字
		String regex = "[\u4E00-\u9FA5]+";
		User user =getModel(User.class);
		if(StrKit.isBlank(user.getUsername())) {
			renderJson(Result.fail("请填写昵称"));
		}else if(user.getUsername().length()>3||!user.getUsername().matches(regex)) {
			renderJson(Result.fail("昵称为中文且不大于3位"));
		}else if(StrKit.isBlank(user.getPhone())) {
			renderJson(Result.fail("请填写手机号"));
		}else if(user.getPhone().length() != 11) {
			renderJson(Result.fail("长度必须为11位"));
		}else if(StrKit.isBlank(user.getPassword())) {
			renderJson(Result.fail("请填写密码"));
		}else {
			if(User.dao.phone(user.getPhone())!=null) {
				renderJson(Result.fail("手机号已存在"));
			}else {
				String userid = IdGenerate.uuid();
				user.setId(userid);
				user.setAvatar(PropKit.get("user.headimg"));
				user.setSign(PropKit.get("user.sign"));
				user.setIsSuperuser("0");
				user.setStatus("hide");
				user.save();
				//创建默认分组
				Group group =new Group();
				group.setId(IdGenerate.uuid());
				group.setGroupname("我的好友");
				group.setUserid(userid);
				group.setSort(0);
				group.save();
				renderJson(Result.success("注册成功"));	
			}
		}
	}
	
	/**
	 * 用户退出
	 */
	public void quit() {
		removeSessionAttr("user");
		renderJson(Result.success("退出成功"));
	}
	
	/**
	 * 用户上线
	 */
	public void online() {
		User user=getSessionAttr("user");
		if(user!=null) {
			
			//修改数据库在线状态
			User.dao.changeStatus(user.getId(),"online");
			//通知在线好友我上线了
			onlineMessage(User.dao.onlineFriend(user.getId()));
			
			renderJson(Result.success("上线成功"));
		}else {
			renderJson(Result.fail("未登录"));
		}
	}
	
	/**
	 * 获取离线消息
	 */
	public void hideMessage() {
		User user=getSessionAttr("user");
		//获取离线消息
		List<Chat> chats=Chat.dao.hidechat(user.getId());
		//离线消息修改为已读
		Chat.dao.updateChatStatus( user.getId());
		
		renderJson(Result.success().add("type", 1).add("data", chats).add("msgbox", Notify.dao.getNotify(user.getId()).size()));
	}
	
	/**
	 * 获取好友分组和群
	 */
	public void friendList() {
		User user=getSessionAttr("user");
		user.setStatus("online");
		//获取所有好友分组
		List<Group> groups=Group.dao.groups(user.getId());
		//获取所加入的群
		List<Bevy> Bevys=Bevy.dao.bevys(user.getId());
		for (Group group : groups) {
			group.put("list", User.dao.friends(group.getId()));
		}
		renderJson(Result.success().add("mine", user).add("friend", groups).add("group", Bevys));
	}
	
	/**
	 * 获取聊天记录
	 */
	public void chatRecord() {
		User user=getSessionAttr("user");
		//如果是好友聊天记录
		if("friend".equals(getPara("type"))) {
			renderJson(Result.success().add("chatRecord", Chat.dao.chatRecord(getPara("id"), user.getId(), getParaToInt("pageNo",1))));
		}else {//如果是群聊天记录
			renderJson(Result.success().add("chatRecord", Chat.dao.groupRecord(getPara("id"), getParaToInt("pageNo",1))));
		}
		
	}
	
	
	/**
	 * 发送消息
	 */
	public void sendMessage() {
		JSONObject messageJson=JSONObject.parseObject(getPara("message"));
		JSONObject mine=messageJson.getJSONObject("mine");
		JSONObject to=messageJson.getJSONObject("to");
		JSONObject message=new JSONObject();
		JSONObject result=new JSONObject();
		
		Chat chat=new Chat();
		chat.setId(IdGenerate.uuid());
		chat.setFromid(mine.getString("id"));
		chat.setContent(mine.getString("content"));
		chat.setType(to.getString("type"));
		chat.setToid(to.getString("id"));
		chat.setTimestamp(new Date().getTime());

		message.put("username", mine.getString("username"));
		message.put("avatar", mine.getString("avatar"));
		message.put("type", to.getString("type"));
		message.put("content", mine.getString("content"));
		message.put("fromid", mine.getString("id"));
		message.put("timestamp", System.currentTimeMillis());
		
		//好友发送消息
		if(to.getString("type").equals("friend")) {
			User user=User.dao.findById(to.getString("id"));
			//判断接收着是否在线
			if(user.getStatus().equals("hide")) {
				chat.setStatus(2);
				//发送信息保存到数据库
				chat.save();
			}else {
				message.put("id", mine.getString("id"));
				chat.setStatus(1);
				//保存到数据库
				chat.save();
	
				result.put("type", 1); 
				result.put("data", message);
				MqttKit.sendMessage(to.getString("id"),result.toJSONString());
			}
		}else { //群组消息
			message.put("id", to.getString("id"));
			chat.setStatus(1);
			//保存到数据库
			chat.save();
			message.put("mine", false);// 是否为我发送 
			result.put("type", 1); 
			result.put("data", message);
			
			List<Bevymember> bevymembers=Bevymember.dao.members(to.getString("id"));
			for (Bevymember bevymember : bevymembers) {
				//不用在给自己发一边
				if(!bevymember.getUseid().equals(mine.getString("id"))) {
					MqttKit.sendMessage(bevymember.getUseid(),result.toJSONString());
				}
			}
		}
		
		renderJson(Result.success());
	}
	
	/**
	 * 聊天发送文件
	 */
	public void uploadImage(){
		 try {
			 //会自动重命名
		       UploadFile file = getFile();
	            renderJson(Result.success("图片发送成功").add("src", "upload/"+file.getFileName()));
	        } catch (Exception e) {
	        	renderJson(Result.fail("图片发送失败"));
	        }
	}
	
	//base64字符串转化成图片  
	public void  GenerateImage() {   //对字节数组字符串进行Base64解码并生成图片  
    	User user = getSessionAttr("user");
    	String imgStr =getPara("finalimg");
    	imgStr=imgStr.replace("data:image/jpeg;base64,", "");
    	imgStr=imgStr.replace("data:image/png;base64,", "");  
    	imgStr=imgStr.replace("data:image/jpg;base64,", "");  
        if (imgStr == null) //图像数据为空  
        	renderJson(Result.fail("修改头像失败"));  
        BASE64Decoder decoder = new BASE64Decoder();  
        try  {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i){  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String headimg = "upload/"+user.getPhone()+".jpg";
            String imgFilePath = PathKit.getWebRootPath()+"/"+headimg;//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            
            user.setAvatar(headimg);
            user.update();
            renderJson(Result.success("修改头像成功").add("src",headimg));
        }  catch (Exception e)   {  
        	renderJson(Result.fail("修改头像失败")); 
        }  
    }  
	
	/**
	 * 查找好友
	 */
	public void lookup() {
		User user = getSessionAttr("user");
		if(getPara("type").equals("friend")) {
			renderJson(Result.success("user", User.dao.lookup(getPara("content"),getParaToInt("pageNo",1),user.getId())));
		}else {
			renderJson(Result.success("user", Bevy.dao.lookup(getPara("content"),getParaToInt("pageNo",1),user.getId())));
		}
	}
	
	/**
	 * 获取群成员
	 */
	public void bevyList() {
		renderJson(Result.success("list", Bevymember.dao.bevyList(getPara("id"))));
	}
	
	/**
	 * 根据id获取好友信息
	 * @param id
	 */
	public void getUserInfo() {
		renderJson(Result.success("user", User.dao.findById(getPara("id"))));
	}
	
	/**
	 * 根据id获取群组信息
	 */
	public void getBevyInfo() {
		renderJson(Result.success("bevy", Bevy.dao.findById(getPara("id"))));
	}
	
	/**
	 * 通知所有在线好友,我上线了
	 * @param users
	 */
	public void onlineMessage(List<User> users) {
		for (User user : users) {
			MqttKit.sendMessage(user.getId(), JsonKit.toJson(Result.success().add("type", MessageType.online.type()).add("user", (User)getSessionAttr("user"))));
		}
	}
	
	/**
	 * 添加好友，添加群
	 */
	public void addFriendGroup() {
		User user = getSessionAttr("user");
		Notify notify = new Notify();
		notify.setId(IdGenerate.uuid());
		notify.setStatus(1);//设置为未读
		notify.setRemark(getPara("remark"));
		notify.setTimestamp(System.currentTimeMillis()+"");
		notify.setFrom(user.getId());
		if("friend".equals(getPara("type"))) {
			notify.setTo(getPara("toid"));
			notify.setHandlerid(getPara("toid"));
			notify.setType(1);
			notify.setGroupid(getPara("groupid"));	
		}else {
			Bevy bevy = Bevy.dao.findById(getPara("toid"));
			notify.setTo(bevy.getBelong());
			notify.setHandlerid(bevy.getBelong());
			notify.setType(3);
			notify.setGroupid(bevy.getId());
		}
		if(Notify.dao.checkNotify(notify.getFrom(), notify.getTo(),notify.getType()).size()>0) {
			renderJson(Result.success("不能重复申请"));
		}else {
			notify.save();
			User toUser = User.dao.findById(notify.getHandlerid());
			if("online".equals(toUser.getStatus())) {
				MqttKit.sendMessage(toUser.getId(),JsonKit.toJson( Result.success("msgbox", Notify.dao.getNotify(notify.getHandlerid()).size()).add("type", 7)));
			}
			renderJson(Result.success("申请发送成功"));
		}
	}
	
	/**
	 * 获取消息通知
	 */
	public void checkFriendGroup() {
		User user = getSessionAttr("user");
		List<Notify> notifies = Notify.dao.getNotify(user.getId());
		for (Notify notify : notifies) {
			if(notify.getType()==3) {
				Bevy bevy = Bevy.dao.findById(notify.getGroupid());
				notify.put("bevyName", bevy.getGroupname());
			}
			notify.put("user", User.dao.findById(notify.getFrom()));
		}
		renderJson(Result.success("notifies", notifies));
		
	}
	
	//同意添加好友
	public void addFriend() {
		String uid = getPara("uid");//对方用户ID
		User fromUser = User.dao.findById(uid);
		String notifieid = getPara("notifieid");
		User user = getSessionAttr("user");
		String fromGroup = getPara("from_group");//对方设定的好友分组
		String myGroup = getPara("group");//我设定的好友分组
		if(Friend.dao.isFriend(uid, user.getId()).size()==0) {
			//将对方添加到我的好友列表
			Friend myfriend = new Friend();
			myfriend.setId(IdGenerate.uuid());
			myfriend.setBelong(user.getId());
			myfriend.setGroupid(myGroup);
			myfriend.setRemark(fromUser.getUsername());
			myfriend.setTimestamp(System.currentTimeMillis());
			myfriend.setUserid(uid);
			myfriend.save();
			//将我添加到对方好友列表
			Friend fromfriend = new Friend();
			fromfriend.setId(IdGenerate.uuid());
			fromfriend.setBelong(uid);
			fromfriend.setGroupid(fromGroup);
			fromfriend.setRemark(user.getUsername());
			fromfriend.setTimestamp(System.currentTimeMillis());
			fromfriend.setUserid(user.getId());
			fromfriend.save();
			
			Notify notify = Notify.dao.findById(notifieid);
			notify.setStatus(2);
			notify.update();
		}else {
			Notify notify = Notify.dao.findById(notifieid);
			notify.setStatus(2);
			notify.update();
		}
		User u = User.dao.findById(uid);
		if("online".equals(u.getStatus())) {
			MqttKit.sendMessage(u.getId(),JsonKit.toJson(Result.success().add("type", 9).add("user", user).add("groupid", fromGroup)));
		}
		renderJson(Result.success());
	}
	
	//同意添加群
	public void addBevy() {
		String notifieid = getPara("notifieid");
		Notify notify = Notify.dao.findById(notifieid);
		User user = User.dao .findById(notify.getFrom());
		Bevymember bevymember = new Bevymember();
		bevymember.setId(IdGenerate.uuid());
		bevymember.setRemark(user.getUsername());
		bevymember.setBevyid(notify.getGroupid());
		bevymember.setStatus(0);
		bevymember.setUseid(user.getId());
		bevymember.setType(0);
		bevymember.setTimestamp(System.currentTimeMillis());
		bevymember.save();
		notify.setStatus(2);
		notify.update();
		if("online".equals(user.getStatus())) {
			MqttKit.sendMessage(user.getId(),JsonKit.toJson(Result.success().add("type", 10).add("notify", notify)));
		}
		renderJson(Result.success());
	}
	
	/**
	 * 拒绝审核
	 */
	public void refuseFriend() {
		String notifieid = getPara("notifieid");
		Notify notify = Notify.dao.findById(notifieid);
		notify.setStatus(3);
		notify.update();
		renderJson(Result.success());
	}
	
	/**
	 * 创建群组
	 */
	public void createGroup() {
		User user = getSessionAttr("user");
		String groupname=getPara("groupname");
		String des=getPara("des");
		String avatar = getPara("avatar","upload/bevy.png");
		Bevy bevy = new Bevy();
		//群id不设置为uuid
		String bevyid = System.currentTimeMillis()+"";
		bevy.setId(bevyid);
		bevy.setBelong(user.getId());
		bevy.setDes(des);
		bevy.setGroupname(groupname);
		bevy.setStatus(0+"");
		bevy.setNumber(1);
		bevy.setTimestamp(System.currentTimeMillis());
		bevy.setAvatar(avatar);
		bevy.save();
		//将自己加入群内
		Bevymember bevymember = new Bevymember();
		bevymember.setStatus(0);
		bevymember.setUseid(user.getId());
		bevymember.setType(1);
		bevymember.setBevyid(bevyid);
		bevymember.setRemark(user.getUsername());
		bevymember.setTimestamp(System.currentTimeMillis());
		bevymember.setId(IdGenerate.uuid());
		bevymember.save();
		renderJson(Result.success().add("bevy", bevy));
	}

	/**
	 * 新建分组
	 */
	public void newGroup() {
		User user = getSessionAttr("user");
		Group group = new Group();
		group.setGroupname(getPara("groupname"));
		group.setId(IdGenerate.uuid());
		group.setSort(0);
		group.setUserid(user.getId());
		group.save();
		renderJson(Result.success().add("group", group));
	}
	
	/**
	 * 修改分组
	 */
	public void updateGroup() {
		User user = getSessionAttr("user");
		int  groupindex = getParaToInt("targetIndex");
		List<Group> groups = Group.dao.groups(user.getId());
		for (int i = 0; i < groups.size(); i++) {
			if(i==groupindex) {
				Group group = groups.get(i);
				group.setGroupname(getPara("groupname","默认分组"));
				group.update();
			}
		}
		renderJson(Result.success());
	}
	
	/**
	 * 删除分组
	 */
	public void deleteGroup() {
		User user = getSessionAttr("user");
		int  groupindex = getParaToInt("targetIndex");
		List<Group> groups = Group.dao.groups(user.getId());
		Group group = null;
		for (int i = 0; i < groups.size(); i++) {
			if(i==groupindex) {
				 group = groups.get(i);
			}
		}
		List<User> friends = User.dao.friends(group.getId());
		if(friends.size()>0) {
			renderJson(Result.fail("该分组下还有好友"));
		}else {
			if(groups.size()==1) {
				renderJson(Result.fail("至少有一个分组"));
			}else {
				group.delete();
				renderJson(Result.success().add("group", group));	
			}

		}
	}
	
	/**
	 * 删除好友
	 */
	public void deleteFriend() {
		User user = getSessionAttr("user");
		User myFriend = User.dao.findById(getPara("uid"));
		List<Friend> friends = Friend.dao.isFriend(myFriend.getId(), user.getId());
		for (Friend friend : friends) {
			friend.delete();
		} 
		if("online".equals(myFriend.getStatus())) {
			MqttKit.sendMessage(myFriend.getId(),JsonKit.toJson(Result.success().add("type", 8).add("user", user)));
		}
		renderJson(Result.success());
	}
	
	/**
	 * 修改好友备注
	 */
	public void updateRemark() {
		User myFriend = User.dao.findById(getPara("uid"));
		User user = getSessionAttr("user");
		Friend friend = Friend.dao.getFriend(myFriend.getId(), user.getId());
		friend.setRemark(getPara("remark"));
		friend.update();
		renderJson(Result.success());
	}
	
	/**'
	 * 获取所有分组
	 */
	public void groups() {
		User user = getSessionAttr("user");
		renderJson(Result.success().add("groups", Group.dao.groups(user.getId())));
	}
	
	public void lookGroupRemark() {
		User user = getSessionAttr("user");
		Bevymember bevymember = Bevymember.dao.getBevyByUser(getPara("uid"), user.getId());
		renderJson(Result.success().add("bevymember", bevymember));
	}
	
	/***
	 * 修改群名片
	 */
	public void modifyBevyRemark() {
		User user = getSessionAttr("user");
		Bevymember bevymember = Bevymember.dao.getBevyByUser(getPara("uid"), user.getId());
		bevymember.setRemark(getPara("remark"));
		bevymember.update();
		renderJson(Result.success());
	}
	
	/**
	 * 退群
	 */
	public void exitGroup() {
		User user = getSessionAttr("user");
		Bevymember bevymember = Bevymember.dao.getBevyByUser(getPara("uid"), user.getId());
		if(bevymember.getType()!=1) {
			bevymember.delete();
			renderJson(Result.success());
		}else {
			List<Bevymember> bevymembers = Bevymember.dao.members(bevymember.getBevyid());
			//只剩群主一个人
			if(bevymembers.size()==1) {
				bevymember.delete();
				Bevy bevy = Bevy.dao.dao().findById(bevymember.getBevyid());
				bevy.delete();
				renderJson(Result.success());
			}else {
				renderJson(Result.fail("群主只可以最后一个退群"));
			}
		}
	}
	
	public void modifySign() {
		User user = getSessionAttr("user");
		User u = User.dao.findById(user.getId());
		u.setSign(getPara("sign"));
		u.update();
		renderJson(Result.success());
	}
}
